package com.edu.study.base.rest;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.edu.study.base.utils.vo.UpdateWordVO;
import com.edu.study.base.wordBook.domain.WordBook;
import com.edu.study.base.wordBook.service.IWordBookService;
import com.edu.study.base.wordBookMember.domain.WordBookMember;
import com.edu.study.base.wordBookMember.service.IWordBookMemberService;
import com.edu.study.base.wordLearn.domain.EduWordLearn;
import com.edu.study.base.wordLearn.service.IEduWordLearnService;
import com.edu.study.base.wordrelation.domain.WordRelation;
import com.edu.study.base.wordrelation.service.IWordRelationService;
import com.edu.study.entities.po.EduWordLearnNew;
import com.edu.study.entities.po.StuStudyProcess;
import com.edu.study.entities.vo.WordCardVO;
import com.edu.study.service.EduWordLearnNewService;
import com.edu.study.service.StuStudyProcessService;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Api(tags = "7、万词通相关接口")
@RestController
@RequestMapping("/api/wct")
public class AppWordLibraryController {

    @Autowired
    private IWordBookService wordBookService;
    @Autowired
    private IEduWordLearnService wordLearnService;
    @Autowired
    private EduWordLearnNewService eduWordLearnNewService;
    @Autowired
    private IWordBookMemberService wordBookMemberService;

    @ApiOperation(value = "添加单词到单词本", hidden = true)
    @PostMapping("AddWordToLearn")
    public AjaxResult AddWordToLearn(@RequestBody UpdateWordVO wordVO) {
        List<EduWordLearnNew> list = eduWordLearnNewService.list(new LambdaQueryWrapper<EduWordLearnNew>()
                .eq(EduWordLearnNew::getMemberId, wordVO.getMemberId())
                .in(EduWordLearnNew::getWordId, wordVO.getWordIds())
//                .in(EduWordLearnNew::getKo, 2)
        );
        Map<String, EduWordLearnNew> learnNewMap = list.stream().collect(Collectors.toMap(EduWordLearnNew::getWordId, v -> v));

        for (String wordId : wordVO.getWordIds()) {
            EduWordLearnNew learn = learnNewMap.getOrDefault(wordId, new EduWordLearnNew());
            learn.setWordSource("1");
            learn.setKo(2);
            learn.setStudyTime(null);
            learn.setWordId(wordId);
            learn.setMemberId(wordVO.getMemberId());

            if (StringUtils.isNotBlank(learn.getId())) {
                eduWordLearnNewService.updateById(learn);
            } else {
                eduWordLearnNewService.save(learn);
            }
        }

        return AjaxResult.success();
    }

    @ApiOperation(value = "获取我的词书")
    @ApiImplicitParam(name = "memberId", value = "会员id", required = true)
    @GetMapping("/getMyWordBook")
    public AjaxResult getMyWordBook(String memberId) {
        WordBookMember wordBookMember = new WordBookMember();
        wordBookMember.setMemberId(memberId);
        wordBookMember.setBookStatus("1");
        return AjaxResult.success(wordBookMemberService.selectMyWordBook(wordBookMember));
    }


    @ApiOperation(value = "获取全部词书")
    @GetMapping("/getWordBooks")
    public AjaxResult getWordBooks() {
        WordBook wordBook = new WordBook();
        wordBook.setBookCategory("1,2");
        return AjaxResult.success(wordBookService.selectWordBookListWithWordNumber(wordBook));
    }

    @Autowired
    private EduWordLearnNewService wordLearnNewService;
    @Autowired
    private StuStudyProcessService stuStudyProcessService;
    @Autowired
    private IWordRelationService wordRelationService;

    @ApiOperation(value = "选择/切换词书")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "memberId", value = "会员id", required = true),
            @ApiImplicitParam(name = "bookId", value = "词书id", required = true)
    })
    @PostMapping("/AddWordBook")
    public AjaxResult AddWordBook(String memberId, Long bookId) {
        // 获取词书信息
        WordBook wordBook = wordBookService.selectWordBookById(bookId);

        WordBookMember wordBookMember = new WordBookMember();
        wordBookMember.setMemberId(memberId);
        List<WordBookMember> wordBookMemberList = wordBookMemberService.selectWordBookMemberList(wordBookMember);
        if (CollectionUtils.isEmpty(wordBookMemberList)) {
            wordBookMember.setBookId(bookId);
            wordBookMember.setBookStatus("1");
            wordBookMemberService.insertWordBookMember(wordBookMember);
        } else {
            List<Long> ids = new ArrayList<>();
            wordBookMemberList.forEach(w -> {
                //如果之前选过相同的词书，就把词书状态更新成1：正在学
                if (bookId.equals(w.getBookId())) {
                    wordBookMember.setId(w.getId());
                    wordBookMember.setBookStatus("1");
                    wordBookMemberService.updateWordBookMember(wordBookMember);
                } else {
                    ids.add(w.getId());
                }
            });
            //新加词书，把之前选的词书状态变成2：已学过
            if (ids.size() == wordBookMemberList.size()) {
                wordBookMemberService.updateBookStatusByIds(StringUtils.join(ids, ","));
                wordBookMember.setBookId(bookId);
                wordBookMember.setBookStatus("1");
                wordBookMemberService.insertWordBookMember(wordBookMember);
            } else if (ids.size() > 0 && ids.size() < wordBookMemberList.size()) {
                wordBookMemberService.updateBookStatusByIds(StringUtils.join(ids, ","));
            }

        }

//        // 获取生词本
//        List<EduWordLearnNew> list = wordLearnNewService.list(new LambdaQueryWrapper<EduWordLearnNew>()
//                .eq(EduWordLearnNew::getMemberId, memberId)
//                .eq(EduWordLearnNew::getKo, 2)
//        );
//        List<String> wordIds = list.stream().map(EduWordLearnNew::getWordId).collect(Collectors.toList());
//
//        // 获取词书生词
//        List<WordRelation> relations = wordRelationService.list(new LambdaQueryWrapper<WordRelation>().eq(WordRelation::getBelongId, wordBook.getId()));
//
//        for (WordRelation relation : relations) {
//            if (wordIds.contains(relation.getWordId())) continue;
//
//            EduWordLearnNew wordLearn = new EduWordLearnNew();
//            wordLearn.setWordSource("2");
//            wordLearn.setWordSourceID(wordBook.getId().toString());
//            wordLearn.setMemberId(memberId);
//            wordLearn.setKo(2);
//            wordLearn.setWordId(relation.getWordId());
//            wordLearnNewService.save(wordLearn);
//        }

//        // 修改每日任务
//        WordCardVO reqWordCardVO = new WordCardVO();
//        reqWordCardVO.setSource('2');
//        reqWordCardVO.setName(wordBook.getBookName());
//        reqWordCardVO.setBookImg(wordBook.getBookImg());
//        reqWordCardVO.setWordCount(0);
//        reqWordCardVO.setWordsMissionNum(0);
//        reqWordCardVO.setTodayWordsMissionCompletedNum(0);
//        reqWordCardVO.setTotalWordsMissionCompletedNum(0);
//        reqWordCardVO.setBookOrCourseId(wordBook.getId().toString());
//        stuStudyProcessService.updateCardMission(reqWordCardVO);

        StuStudyProcess process = stuStudyProcessService.getCurrentUserStudyProcess();
        process.setBookId(bookId);
        stuStudyProcessService.updateById(process);

        return AjaxResult.success();
    }

    @ApiOperation(value = "获取魔幻乘方爆炸式学单词的目录")
    @GetMapping("/getWordGroup")
    public AjaxResult getWordGroup() {
        WordBook wordBook = new WordBook();
        //wordBook.setParentId(0L);
        wordBook.setBookCategory("3");
        List<WordBook> wordBooks = wordBookService.selectWordBookList(wordBook);
        List<WordBook> roots = wordBooks.stream().filter(w -> w.getParentId() == 0).collect(Collectors.toList());
        roots.forEach(r -> {
            //List<WordBook> children = wordBooks.stream().filter(w -> r.getId().equals(w.getParentId())).collect(Collectors.toList());
            //r.setChildren(children);
            BuilderTree(r, wordBooks);
        });

        return AjaxResult.success(roots);
    }

    private void BuilderTree(WordBook wordBook, List<WordBook> WordBookList) {
        List<WordBook> children = WordBookList.stream().filter(w -> wordBook.getId().equals(w.getParentId())).collect(Collectors.toList());
        wordBook.setChildren(children);
        children.forEach(c -> {
            BuilderTree(c, WordBookList);
        });

    }

}
